package com.openvid.webrtc.openvid.cmd;

import com.google.gson.Gson;
import com.openvid.webrtc.openvid.websocket.IWebSocket;

import org.json.JSONException;
import org.json.JSONObject;

public abstract class AbsRequestCmd<T> {

    private static final String JSON_RPCVERSION = "2.0";

    private Gson mGson = new Gson();

    protected abstract String getMethodName();

    protected abstract Object getParams();

    protected abstract Class<T> getResponseClass();

    private WsCmdCallback<T> mCallback;

    public void setCallback(WsCmdCallback<T> c) {
        this.mCallback = c;
    }

    private int mRequestId = -1;

    public int getRequestId() {
        return mRequestId;
    }

    public  String getMethodTag(){
        return getMethodName();
    }

    public int request(int id, IWebSocket socket) {
        mRequestId = id;
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("jsonrpc", JSON_RPCVERSION);
            jsonObject.put("method", getMethodName());
            jsonObject.put("id", id);
            Object paramsObj=getParams();
            if (paramsObj!=null){
                String paramsStr = mGson.toJson(paramsObj);
                jsonObject.put("params", new JSONObject(paramsStr));
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
        socket.sendMsg(jsonObject.toString());
        return id;
    }

    public int timeOutSeconds() {
        return 10;
    }

    public void onResponse(String jsonResponse) {
        T resp = mGson.fromJson(jsonResponse, getResponseClass());
        if (mCallback!=null){
            mCallback.onAction(resp);
        }
    }
}
